import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import Login from "../views/Login.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    component: Login,
    name: "login",
  },
  {
    path: "/home",
    component: Home,
    name: "home",    
  },
];

const router = new VueRouter({
  mode: "hash",
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.path == "/") {
    next();
  } else {
    let userMenus = sessionStorage.getItem("userMenus");
    if (userMenus) {
      //已经登录成功了
      let routerArr = router.getRoutes();
      if (routerArr.length > 4) {
        //创建过路由
        next();
      } else {
        //没创建路由，刷新了
        JSON.parse(userMenus).forEach((v) => {
          if (v.children == null) {
            router.addRoute("home", {
              path: v.href,
              component: () => import(`@/views/${v.component}.vue`),
            });
          } else {
            v.children.forEach((v2) => {
              if (v2.children == null && v2.href != null) {
                router.addRoute("home", {
                  path: v2.href,
                  component: () => import(`@/views/${v2.component}.vue`),
                });
              } else {
                if (v2.children) {
                  v2.children.forEach((v3) => {
                    router.addRoute("home", {
                      path: v3.href,
                      component: () => import(`@/views/${v3.component}.vue`),
                    });
                  });
                }
              }
            });
          }
        });
        next({ ...to, replace: true });
      }
    } else {
      //没有登录成功
      // console.log("没登录成功");
      next({ path: "/login", replace: true });
    }
  }
});

export default router;
